<template>
  <div class="normal-setting-box flex">
    <div class="user-card-setting" v-if="isShowFeatureSet">
      <el-row class="box-item" :gutter="15">
        <el-col :span="16">
          <p class="item-title">{{$t('setting.common.userCard.openUserCard')}}</p>
          <p class="item-text">{{$t('setting.common.userCard.tip.openCardTip')}}</p>
        </el-col>
        <el-col :span="8" class="user-card-switch">
          <el-switch
            class="setting—box-switch"
            v-model="showCard"
            @change="changeShowCard">
          </el-switch>
        </el-col>
      </el-row>
      <template v-if="showCard">
        <div class="box-item user-card-box" style="display:block">
          <p class="item-title">{{$t('setting.common.userCard.userCardSetting')}}</p>
          <div class="item-content">
            <span class="item-tip">{{$t('setting.common.userCard.cardShow')}}</span>
            <el-checkbox
              v-for="item in detailList"
              :key="item.name"
              v-model="cardFieldConfig[item.name]"
              @change="changeCardFields">{{ item.label }}</el-checkbox>
            <span>({{$t('setting.common.userCard.tip.authTip')}},<el-button type="text" @click="goRoleSetting">{{$t('common.base.toSet2')}}</el-button>)</span>
          </div>
          <div :class="['user-card-demo',showIm?'biz-user-card-im':'']">
            <div class="biz-user-card-header">
              <img :src="defaultAvatar" alt="" class="avatar">
              <div class="state">
                <div class="state-top">
                  <span class="user-name">{{$t('setting.common.userCard.demoName')}}</span>
                  <div class="work-state">            
                    <i class="contact-user-state-icon" style="backgroundColor: rgb(110, 207, 64);"></i> 
                    <span>{{$t('common.base.usualStatus.working')}}</span>
                  </div>
                </div>
                <div class="state-bottom">{{$t('common.base.publink2')}}</div>
              </div>
              <div class="right-arrow" v-if="cardFieldConfig.showUserDetail"><i class="iconfont icon-right"></i></div>
            </div>
            <div class="biz-user-card-main">
              <div class="biz-user-info" v-if="cardFieldConfig.showCalendar&&showCalendarSwitch">
                <div class="user-form-item">
                  <div class="user-card-label">{{$t('common.schedule.title')}}：</div>
                  <div class="user-card-content">
                    <span :style="{color: getThemeColor}">{{$t('common.schedule.viewStatus')}}</span>
                  </div>
                </div>
              </div>
              <div class="calendar-devider" v-if="cardFieldConfig.showCalendar"></div>
              <div class="biz-user-info">
                <div class="user-form-item" v-if="cardFieldConfig.showPhone">
                  <div class="user-card-label">{{$t('common.fields.phone.displayName')}}：</div>
                  <div class="user-card-content">134xxxx1234</div>
                </div>
                <div class="user-form-item" v-if="cardFieldConfig.showEmail && _isShowEmail">
                  <div class="user-card-label">{{$t('common.fields.email.displayName')}}：</div>
                  <div class="user-card-content">xxxx@xxx.com</div>
                </div>
                <div class="user-form-item" v-if="cardFieldConfig.showDepartment">
                  <div class="user-card-label">{{$t('common.fields.department.displayName')}}：</div>
                  <div class="user-card-content">{{$t('setting.common.userCard.technologyDepartment')}}</div>
                </div>
                <div class="user-form-item" v-if="cardFieldConfig.showRole">
                  <div class="user-card-label">{{$t('common.fields.role.displayName')}}：</div>
                  <div class="user-card-content">{{$t('common.auth.roleNameList[0]')}}</div>
                </div>
              </div>
              <div class="user-card-im" v-if="showIm">
                <div class="user-card-im-btn">{{$t('common.base.sendMessage')}}</div>
              </div>
            </div>
          </div>
        </div>
        <el-row class="box-item" :gutter="15" style="margin-bottom:12px;">
          <el-col :span="18">
            <p class="item-title">{{$t('setting.common.userCard.hideSomeUserInfo')}}</p>
            <p class="item-text">{{$t('setting.common.userCard.singleShow')}}</p>
            <div style="margin-top:4px;">
              <el-button type="primary" @click="addRule" icon="el-icon-plus">{{$t('common.base.create')}}</el-button>
            </div>
          </el-col>
          <el-col :span="6" style="text-align:right;">
          </el-col>
        </el-row>
        <el-table
          :data="sensitiveList"
          v-loading="loading"
        >
          <el-table-column
            :label="$t('setting.common.userCard.deptOrMember')"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              {{transformText(row.sensitiveMembers)}}
            </template>
        
          </el-table-column>
          <el-table-column
            :label="$t('task.setting.taskSetting.text24')"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              {{transformHideText(row)}}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('setting.common.userCard.whiteList')"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              {{transformText(row.whiteList)}}
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            :label="$t('common.base.operation')"
            fixed="right"
            width="140"
          >
            <template slot-scope="{row}">
              <el-button type="text" @click="editRule(row)">{{$t('common.base.edit')}}</el-button>
              <el-button type="text" class="danger-text" @click="deleteRule(row)">{{$t('common.base.delete')}}</el-button>
            </template>
          </el-table-column>
        </el-table>

      </template>
      <el-row class="box-item im-setting" :gutter="15" style="margin-top:36px;" v-if="showImSwitch">
        <el-col :span="16">
          <p class="item-title">{{$t('setting.common.userCard.openImFunction')}}</p>
          <p class="item-text">{{$t('setting.common.userCard.tip.openImTip')}}</p>
        </el-col>
        <el-col :span="8" class="user-card-switch">
          <el-switch
            class="setting—box-switch"
            v-model="showIm"
            @change="changeShowIm"
            :active-color="getThemeColor">
          </el-switch>
        </el-col>
      </el-row>

      <template v-if="openMessageReform">
        <el-row class="box-item" :gutter="15" style="margin-top:36px;margin-bottom:20px;">
          <el-col :span="16">
            <p class="item-title">{{tenantType == 0 ? $t('setting.common.userCard.openApproveTitle1') : $t('setting.common.userCard.openApproveTitle2')}}</p>
            <p class="item-text">{{tenantType == 0 ? $t('setting.common.userCard.openApproveTitle3') : $t('setting.common.userCard.openApproveTitle4')}}</p>
          </el-col>
          <el-col :span="8" class="user-card-switch">
            <el-switch
              class="setting—box-switch"
              v-model="messageConfig.toBeDoneTipsSwitch"
              @change="changeState($event)"
              :active-color="getThemeColor">
            </el-switch>
          </el-col>
        </el-row>

        <el-row v-if="tenantType == 0 && messageConfig.toBeDoneTipsSwitch" class="box-item" :gutter="15" style="margin-bottom:20px;">
          <el-col :span="16">
            <p class="item-title">{{$t('setting.common.userCard.taskAndEventApprove')}}</p>
          </el-col>
          <el-col :span="8" class="user-card-switch">
            <el-switch
              class="setting—box-switch"
              :value="true"
              disabled
              :active-color="getThemeColor">
            </el-switch>
          </el-col>
        </el-row>

        <el-row v-if="tenantType == 0 && messageConfig.toBeDoneTipsSwitch" class="box-item" :gutter="15" style="margin-bottom:20px;">
          <el-col :span="16">
            <p class="item-title">{{$t('setting.common.userCard.openSpareInstockApprove')}}</p>
          </el-col>
          <el-col :span="8" class="user-card-switch">
            <el-switch
              class="setting—box-switch"
              v-model="messageConfig.sparepartMessageState"
              @change="changeSparepartMessage($event)"
              :active-color="getThemeColor">
            </el-switch>
          </el-col>
        </el-row>

      </template>

      <el-row class="box-item" :gutter="15" style="margin-bottom: 0px;">
        <el-col :span="16">
          <p class="item-title">{{ $t('setting.common.userCard.openSystemWaterMark') }}</p>
          <p class="item-text">{{ $t('setting.common.userCard.openSystemWaterMarkTips') }}</p>
        </el-col>
        <el-col :span="8" class="user-card-switch">
          <el-switch
            class="setting—box-switch"
            v-model="watermarkConfig.enableSwitch"
            @change="updateWatermarkConfig"
            :active-color="getThemeColor">
          </el-switch>
        </el-col>
      </el-row>
      <div class="box-item" v-if="watermarkConfig.enableSwitch">
        <div class="item-content">
          <span class="mr_16 item-tip">{{$t('setting.common.userCard.systemWaterMark')}}</span>
          <el-checkbox
            v-for="item in watermarkConfigList"
            :key="item.name"
            :disabled="['showName', 'showPhone'].includes(item.name) && watermarkConfig[item.name]"
            v-model="watermarkConfig[item.name]"
            @change="updateWatermarkConfig"
          >{{ item.label }}</el-checkbox>
          <input class="ml_16" type="text" v-model="watermarkConfig.customCopyWriting" :placeholder="$t('setting.common.userCard.systemWaterMarkPlaceHolder')" :maxLength="10" @blur="updateWatermarkConfig" />
        </div>
      </div>
    </div>

    <sensitive-rule-dialog ref="ruleDialog" :show-calendar-switch="showCalendarSwitch" @ruleSuccess="getRules"/>
  </div>
</template>

<script>
import { t } from 'src/locales'
import { getRootWindowInitData } from '@src/util/window'
import * as SettingApi from '@src/api/SettingApi'
import * as UserCardApi from '@src/api/UserCard'
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import RuleDialog from './components/ruleDialog.vue'
import _ from 'lodash'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

/** mixin */
import { VersionControlOtherMixin } from '@src/mixins/versionControlMixin'
import { isNotOnlyCustomerServiceCloudVersion } from '@src/util/version'

export default {
  name:'user-card-setting',
  mixins: [VersionControlOtherMixin],
  components:{
    [RuleDialog.name]:RuleDialog
  },
  data(){
    return{
      openMessageReform: false,
      messageConfig: {},
      loading:false,
      defaultAvatar,
      showCard:false,
      showIm:false,
      showImSwitch:false,
      showCalendarSwitch:false,
      cardFieldConfig:{
        showPhone:false,
        showEmail:false,
        showDepartment:false,
        showRole:false,
        showCalendar:false,
        showUserDetail:false
      },
      hideList:[
        {label: t('common.fields.phone.displayName'), name: 'hidePhone'},
        {label: t('common.fields.email.displayName'), name: 'hideEmail'},
        {label: t('common.fields.department.displayName'), name: 'hideDepartment'},
        {label: t('common.fields.role.displayName'), name: 'hideRole'},
        {label: t('setting.common.userCard.displayName.calendar'), name: 'hideCalendar'},
        {label: t('setting.common.userCard.displayName.userDetail'), name: 'hideUserDetail'}
      ],
      watermarkConfig: {},
      watermarkConfigList:[
        {label: t('common.base.fullName'), name: 'showName'},
        {label: t('setting.common.userCard.systemWaterMarkConfig1'), name: 'showPhone'},
        {label: t('common.base.companyName2'), name: 'showCompanyName'},
        {label: t('product.component.qrcodeDialog.companyName'), name: 'showCompanyAbbreviation'},
        {label: t('common.base.date'), name: 'showDate'},
        {label: t('common.base.custom'), name: 'showCopyWriting'}
      ],
      sensitiveList:[
      ],
			isShowFeatureSet:false
    }
  },
  created(){
    this.getConfig()
    this.getRules()
    this.getWatermarkConfig()
    const rootWindowInitData = getRootWindowInitData()
    let { openMessageReform, tenantType } = rootWindowInitData 
    // 钉钉端和飞书端开启消息设置灰度显示钉钉、飞书代办
    this.tenantType = tenantType
    this.openMessageReform = openMessageReform && (tenantType == 0 || tenantType == 4) && isNotOnlyCustomerServiceCloudVersion()
    if(this.openMessageReform) {
      // 获取消息
      this.getDDMessageConfig()
    }
  },
  computed:{
    detailList(){
      let arr = [
        {label: t('common.fields.phone.displayName'), name: 'showPhone'},
        {label: t('common.fields.email.displayName'), name: 'showEmail'},
        {label: t('common.fields.department.displayName'), name: 'showDepartment'},
        {label: t('common.fields.role.displayName'), name: 'showRole'},
        {label: t('setting.common.userCard.displayName.calendar'), name: 'showCalendar'},
        {label: t('setting.common.userCard.displayName.userDetail'), name: 'showUserDetail'}
      ]
      if(!this._isShowEmail) {
        arr = arr.filter(item => item.name != 'showEmail')
      }
      if(this.showCalendarSwitch) {
        return arr
      }
      return arr.filter(item => item.name != 'showCalendar')
    }
  },
  methods:{
    async getDDMessageConfig() {
			try {
				const { status, data, message } = await SettingApi.getDDMessageConfig();
				if(status) return this.$platform.toast(message, 'error');
			  this.messageConfig = data.messageConfig; 
			} catch (error) {
				console.log(error);
			}
		},
    // 改变模板开启禁用
		async changeState(state) {
			try {
        const params = {state, message: 'toBeDoneTipsSwitch'};
        // 这里判断是钉钉端还是飞书端
        let task 
        if(this.tenantType == 0) {
          task = SettingApi.saveTaskDdmessage(params);
        } else if(this.tenantType == 4) {
          task = SettingApi.saveLarkApproveState(params);
        }
				const { status, message, data } = await task;
				if(status) return this.$platform.toast(message, 'error');
				this.messageConfig = data.messageConfig;
			} catch (error) {
				console.log(error);
			}
		},
    // 改变启用备件出入库审批
    async changeSparepartMessage(state) {
			try {
				const { status, message } = await SettingApi.updateSparepartMessageConfig({state: state ? 0 : 1});
				if(status) return this.$platform.toast(message, 'error');;
			} catch (error) {
				console.log(error);
			}
		},
    getConfig(){
      UserCardApi.getUserCardConfig().then(res=>{
        if(res.status == 0){
          let data = res.data
          this.showCard = data.showCard
          this.showIm = data.showIm
          // this.showImSwitch = data.authIm || false
          this.showCalendarSwitch = data.authCalendar || false
          this.cardFieldConfig = data.cardFieldConfig

					// 控制页面显示隐藏--放到最后
					this.isShowFeatureSet = true;
        }else{
          this.$platform.toast(res.message, 'error')
        }
      })
      UserCardApi.getIsShowIm().then(res=>{
        if(res.status == 0){
          this.showImSwitch = res.data || false
          if(this.showImSwitch&&this.$route.query?.type=='im'){
            this.$nextTick(()=>{
              this.scrollToView('.im-setting');
            })
          }
        }
      })
    },
    goRoleSetting(){
      // this.$platform.openTab({
      //   id:'role_view',
      //   title: '角色管理',
      //   url: '/security/role/view',
      //   reload: true,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityRoleView
      })
    },
    getRules(){
      this.loading = true
      UserCardApi.getUserCardRuleList().then(res=>{
        if(res.status == 0){
          this.sensitiveList = res.data
        }else{
          this.$platform.toast(res.message, 'error')
        }
      }).finally(()=>{
        this.loading = false
      })
    },
    addRule(){
      if(this.sensitiveList.length > 9){
        return this.$platform.alert(t('setting.common.userCard.tip.maxLimit', {count: 10}))
      }
      this.$refs.ruleDialog.open()
    },
    editRule(row){
      let form = _.cloneDeep(row)
      this.$refs.ruleDialog.open(form)
    },
    changeShowCard(){
      UserCardApi.updateUserCardShow(this.showCard).then(res=>{
        if(res.status != 0){
          this.$platform.toast(res.message, 'error')
        }
      })
    },
    changeShowIm(){
      UserCardApi.updateUserCardShowIm(this.showIm).then(res=>{
        if(res.status != 0){
          this.$platform.toast(res.message, 'error')
        }
      })
    },
    changeCardFields(){
      UserCardApi.updateUserCardFieldConfig(this.cardFieldConfig).then(res=>{
        if(res.status != 0){
          this.$platform.toast(res.message, 'error')
        }
      })
    },
    transformText(val){
      let depts = (val.departments || []).map(item=>{return item.deptName})
      let users = (val.staffList || []).map(item=>{return item.staffName})
      return depts.concat(users).join('、')
    },
    transformHideText(val){
      let cardFieldConfig = val.hideFields || {}
      return this.hideList.filter(item=>{return cardFieldConfig[item.name]}).map(item=>{return item.label}).join('、')
    },
    async deleteRule(row){
      if (!(await this.$platform.confirm(t('setting.common.userCard.tip.confirmDelete')))) return;
      UserCardApi.deleteUserCardRule(row.id).then(res=>{
        if(res.status == 0){
          this.getRules()
          this.$platform.toast(t('common.base.tip.deleteSuccess'), 'success')
        }
      })
    },
    scrollToView(className){
			setTimeout(() => {
				let target = document.querySelector(className);
				target && target.scrollIntoView({
					behavior: 'smooth',
					block: 'start',
					inline: 'start',
				});
			}, 1000);
		},
    getWatermarkConfig() {
      UserCardApi.getWatermarkConfig()
        .then(res => {
          if (res.success) {
            this.watermarkConfig = res.data || {}
          }
        }).catch(err => console.error(err))
    },
    updateWatermarkConfig() {
      UserCardApi.updateWatermarkConfig(this.watermarkConfig)
        .then(res => {
          if (!res.success) {
            return this.$platform.toast(res.message, 'error')
          }
        }).catch(err => console.error(err))
    },
  }
}
</script>

<style lang="scss" scoped>
.normal-setting-box{
  display: flex;
  width: 100%;
  padding: 12px;
  height: 100vh;
}
.user-card-setting{
  width: 100%;
  padding:20px;
  border-radius: 4px;
  background: #ffffff;
  overflow-y: auto;
  height:100%;
  .box-item{
    display: flex;
    align-items: center;
    margin-bottom: 36px;
    color:#262626;
    &.user-card-box{
      align-items: flex-start;
    }
    p{
      margin:0;
      padding:0;
    }
    .item-title{
      font-size: 14px;
      font-weight: bold;
      line-height: 18px;
    }
    .item-text,.item-content{
      font-size: 14px;
      line-height: 28px;
      margin-top: 5px;
      color:#8c8c8c;
    }
    .user-card-switch{
      text-align: right;
    }

  }
  .user-card-demo{
    position: relative;
    top: 0!important;
    margin-top:12px;
  }
  .danger-text{
    color:$color-danger!important;
  }
}
  
</style>
<style lang="scss">
.user-card-setting{
  .el-table{
    // border:1px solid #ebeef5;
    // border-bottom:none;
    // border-right:none;
    thead{
      th{
        background-color: #FAFAFA;
        color: #333;
      }
    }
  }
}
</style>